package com.wx.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wx.client.SysSmsClient;
import com.wx.common.BaseEntity;
import com.wx.common.PageParam;
import com.wx.constants.Constants;
import com.wx.constants.RedisKeyPrefix;
import com.wx.domain.dto.DayReportQueryParam;
import com.wx.domain.dto.SysPatientFollowDto;
import com.wx.domain.vo.*;
import com.wx.entity.*;
import com.wx.enums.*;
import com.wx.exception.BusinessException;
import com.wx.mapper.SysPatientFollowMapper;
import com.wx.service.*;
import com.wx.utils.SnowFlakeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * <p>Title:      SysPatientFollowServiceImpl. </p>
 * <p>Description  </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>
 * @since 2021/3/27 21:37
 */
@Service
public class SysPatientFollowServiceImpl extends BaseServiceImpl<SysPatientFollow> implements SysPatientFollowService {

    @Resource
    private SysPatientFollowMapper sysPatientFollowMapper;

    @Resource
    private SysGeneratorCodeService sysGeneratorCodeService;

    @Resource
    private SysNurseService sysNurseService;

    @Resource
    private SysRangeHospitalService sysRangeHospitalService;

    @Resource
    private SysPatientService sysPatientService;

    @Resource
    private SysSmsClient sysSmsClient;

    @Resource
    private SysRangeNurseService sysRangeNurseService;

    @Resource
    private SysAddressService sysAddressService;

    @Resource
    private SysPatientFollowService sysPatientFollowService;

    @Resource
    private SysNotepadService sysNotepadService;

    @Resource
    private SysHospitalService sysHospitalService;

    @Resource
    private SysAgreementService sysAgreementService;

    @Resource
    private SysRangeService sysRangeService;

    @Override
    @Transactional
    public void fistFollowPatient(SysPatientFollow sysPatientFollow, String openid, String nickname) {
        SysPatient patient = sysPatientService.selectByKey(sysPatientFollow.getPatientId());
        if (patient == null) {
            throw new BusinessException("患者信息不存在");
        }
        if (Constants.YES.equals(patient.getAuditStatus()) && Constants.YES.equals(patient.getStatus())) {
            throw new BusinessException("该患者已经完成首次认证，不可重复提交");
        }
        SysNurse sysNurse = sysNurseService.selectByOpenId(openid);
        if (sysNurse == null) {
            throw new BusinessException("您的openId对应的护士信息不存在");
        }

        // 从json字符串中解析患者是否是已处方患者
        String content = sysPatientFollow.getContent();
        JSONObject jsonObject = JSON.parseObject(content);
        logger.info("===> jsonObject = {}", jsonObject.toJSONString());
        String isPrescription = jsonObject.getString("question16");
        JSONObject prescriptionData = JSON.parseObject(isPrescription);

        patient.setId(sysPatientFollow.getPatientId());
        patient.setAuditStatus(Constants.YES);
        patient.setFollowCount(Constants.YES);
        patient.setNurseId(sysNurse.getId());
        patient.setJoinTime(patient.getJoinTime());

        if (Constants.YES_STRING.equals(prescriptionData.getString("val"))) {
            patient.setId(sysPatientFollow.getPatientId());
            patient.setPrescription(Constants.YES);
            patient.setPrescriptionNumber(patient.getPrescriptionNumber() + 1);
            patient.setPrescriptionTime(new Date());
            patient.setCurrentTreatmentBrand("安佳因");
        }

        String changeHospital = jsonObject.getString("question33");
        JSONObject changeHospitalObj = JSON.parseObject(changeHospital);
        String patientChangeHospital = changeHospitalObj.getString("val");
        if (Constants.YES_STRING.equals(patientChangeHospital)) {
            // 转诊省份和城市
            String addressJson = jsonObject.getString("question33.1");
            JSONObject addressObj = JSON.parseObject(addressJson);
            String address = addressObj.getString("id");
            if (!StringUtils.isEmpty(address)) {
                String[] addressSplit = address.split("_");
                patient.setJoinProvinceId(addressSplit[0]);
                patient.setJoinCityId(addressSplit[1]);
            }

            // 转诊医院名称
            String hospital = jsonObject.getString("question33.2");
            JSONObject hospitalObj = JSON.parseObject(hospital);
            String hospitalId = hospitalObj.getString("id");
            patient.setHospitalId(hospitalId);
            // 查询这个医院所对应的护士信息
            SysRangeHospital sysRangeHospital = sysRangeHospitalService.selectByHospitalId(hospitalId);
            if (sysRangeHospital == null) {
                throw new BusinessException("转诊的医院没有绑定对应的所属范围");
            }
            List<SysRangeNurse> sysRangeNurses = sysRangeNurseService.selectByRangeIds(Collections.singletonList(sysRangeHospital.getRangeId()));
            Optional<SysRangeNurse> firstNurse = sysRangeNurses.stream().findFirst();
            firstNurse.ifPresent(sysRangeNurse -> patient.setNurseId(sysRangeNurse.getNurseId()));
        }

        String changeReason = jsonObject.getString("question16.3");
        JSONObject changeReasonData = JSON.parseObject(changeReason);
        patient.setChangeReason(changeReasonData.getString("val"));

        String status = jsonObject.getString("question25");
        JSONObject statusObj = JSON.parseObject(status);
        String patientStatus = statusObj.getString("val");
        if (PatientStatusEnum.IN_GROUP.getDesc().equals(patientStatus)) {
            patient.setAuditStatus(Constants.YES);
        } else if (PatientStatusEnum.LEAVE_GROUP.getDesc().equals(patientStatus)) {
            String exitReason = jsonObject.getString("question25.1");
            JSONObject reasonObj = JSON.parseObject(exitReason);
            String reason = reasonObj.getString("val");
            patient.setRemarks(reason);
            patient.setAuditStatus(Constants.TWO);
            patient.setExitTime(new Date());
            // 如果是脱组需要将之后的随访记录都删除
            sysPatientFollowMapper.deleteInvalidFollows(sysPatientFollow.getPatientId());
        }

        // 患者类型
        String userTypeJson = jsonObject.getString("question1");
        JSONObject userTypeData = JSON.parseObject(userTypeJson);
        patient.setPatientType(StringUtils.isEmpty(userTypeData.getString("val")) ? -1 : PatientTypeEnum.getKey(userTypeData.getString("val")));

        // 年龄
        String ageJson = jsonObject.getString("question2");
        JSONObject ageData = JSON.parseObject(ageJson);
        if (StringUtils.hasText(ageData.getString("val"))) {
            patient.setAge(ageData.getString("val"));
        }

        // 性别
        String sexJson = jsonObject.getString("question3");
        JSONObject sexData = JSON.parseObject(sexJson);
        String val = sexData.getString("val");
        patient.setSex(StringUtils.isEmpty(val) ? 0 : SexEnum.getKey(val));

        // 身高
        String heightAndWeightJson = jsonObject.getString("question13");
        JSONObject heightAndWeightData = JSON.parseObject(heightAndWeightJson);
        patient.setHeight(new BigDecimal(heightAndWeightData.getString("height")));
        // 体重
        patient.setWeight(new BigDecimal(heightAndWeightData.getString("weight")));

        // 当前治疗方案
        String treatmentPlansJson = jsonObject.getString("question11");
        JSONObject treatmentPlanData = JSON.parseObject(treatmentPlansJson);
        String planDataString = treatmentPlanData.getString("text");
        patient.setTreatmentPlan(TreatmentPlanEnum.getKey(planDataString));

        // 治疗剂量
        String treatmentDosageJson = jsonObject.getString("question12");
        JSONObject treatmentDosageData = JSON.parseObject(treatmentDosageJson);
        String treatmentDosageString = treatmentDosageData.getString("val");
        patient.setDosage(treatmentDosageString);
        // 频率
        String dosageFrequencyString = treatmentDosageData.getString("val2");
        patient.setDosageFrequency(dosageFrequencyString);

        // 医保限额
        String isLimitMoneyJson = jsonObject.getString("question7");
        JSONObject isLimitMoneyData = JSON.parseObject(isLimitMoneyJson);
        String islimitMoneyString = isLimitMoneyData.getString("val");
        if (StringUtils.hasText(islimitMoneyString)) {
            patient.setMedicalInsuranceLimit(Constants.YES_STRING.equals(islimitMoneyString) ? Constants.YES : Constants.NO);
        }

        // 医保限额
        String limitMoneyJson = jsonObject.getString("question7.1");
        JSONObject limitMoneyData = JSON.parseObject(limitMoneyJson);
        String limitMoneyString = limitMoneyData.getString("val");
        patient.setMedicalInsuranceLimitMoney(limitMoneyString);

        sysPatientService.update(patient);


        List<SysPatientFollow> list = Lists.newArrayList();

        List<SysHospital> sysHospitals = sysHospitalService.selectByIds(Collections.singletonList(patient.getHospitalId()));
        Optional<SysHospital> first = sysHospitals.stream().findFirst();
        if(first.isPresent()){
            SysHospital sysHospital = first.get();
            sysPatientFollow.setRangeId(sysHospital.getRangeId());
            sysPatientFollow.setHospitalType(sysHospital.getHospitalType());
            sysPatientFollow.setJoinProvinceId(sysHospital.getProvinceCode());
            sysPatientFollow.setJoinCityId(sysHospital.getCityCode());
            sysPatientFollow.setRegion(sysHospital.getRegion());
            sysPatientFollow.setBigRegion(sysHospital.getBigRegion());
        }
        sysPatientFollow.setId(SnowFlakeUtil.getStringId());
        String uuid = sysGeneratorCodeService.fetchUUID(RedisKeyPrefix.PATIENT_FOLLOW_KEY, 6, false);
        sysPatientFollow.setFollowCode("PF" + uuid);
        sysPatientFollow.setFollowTime(new Date());
        sysPatientFollow.setStatus(Constants.YES);
        sysPatientFollow.setCreateBy(openid);
        sysPatientFollow.setCreator(nickname);
        sysPatientFollow.setUpdateBy(openid);
        sysPatientFollow.setUpdater(nickname);
        sysPatientFollow.setType(Constants.NO);
        sysPatientFollow.setSerialNumber(Constants.YES);
        sysPatientFollow.setHospitalId(patient.getHospitalId());
        sysPatientFollow.setNurseId(patient.getNurseId());
        sysPatientFollow.setPatientName(patient.getRealName());
        sysPatientFollow.setPrescription(patient.getPrescription());
        sysPatientFollow.setChangeReason(patient.getChangeReason());
        sysPatientFollow.setJoinTime(patient.getJoinTime());
        list.add(sysPatientFollow);

        // 生成将来的随访记录
        createFuturePatientFollow(list, openid, nickname, sysPatientFollow);

        sysPatientFollowMapper.batchInsert(list);

        try {
            sysSmsClient.sendSms(new String[]{"+86" + patient.getPhone()}, SmsTemplateEnum.TEMPLATE_2.getKey(), new String[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成将来的随访记录
     */
    private void createFuturePatientFollow(List<SysPatientFollow> list, String openId, String nickName, SysPatientFollow fistPatientFollow) {
        SysPatientFollow sysPatientFollow = null;
        Date preDate = new Date();
        for (int i = 1; i <= 14; i++) {
            sysPatientFollow = new SysPatientFollow();
            sysPatientFollow.setId(SnowFlakeUtil.getStringId());
            sysPatientFollow.setPatientId(fistPatientFollow.getPatientId());
            sysPatientFollow.setPatientName(fistPatientFollow.getPatientName());
            sysPatientFollow.setPrescription(fistPatientFollow.getPrescription());
            sysPatientFollow.setChangeReason(fistPatientFollow.getChangeReason());
            sysPatientFollow.setJoinTime(fistPatientFollow.getJoinTime());
            sysPatientFollow.setHospitalId(fistPatientFollow.getHospitalId());
            sysPatientFollow.setHospitalType(fistPatientFollow.getHospitalType());
            sysPatientFollow.setRegion(fistPatientFollow.getRegion());
            sysPatientFollow.setBigRegion(fistPatientFollow.getBigRegion());
            sysPatientFollow.setRangeId(fistPatientFollow.getRangeId());
            sysPatientFollow.setJoinProvinceId(fistPatientFollow.getJoinProvinceId());
            sysPatientFollow.setJoinCityId(fistPatientFollow.getJoinCityId());
            sysPatientFollow.setNurseId(fistPatientFollow.getNurseId());
            sysPatientFollow.setCreateBy(openId);
            sysPatientFollow.setCreator(nickName);
            sysPatientFollow.setUpdateBy(openId);
            sysPatientFollow.setUpdater(nickName);
            sysPatientFollow.setStatus(Constants.NO);
            sysPatientFollow.setType(Constants.NO);
            sysPatientFollow.setContent("");
            sysPatientFollow.setSerialNumber(i + 1);
            String uuid = sysGeneratorCodeService.fetchUUID(RedisKeyPrefix.PATIENT_FOLLOW_KEY, 6, false);
            sysPatientFollow.setFollowCode("PF" + uuid);
            sysPatientFollow.setFollowTime(DateUtil.offsetDay(preDate, 7));
            if (i > 3) {
                sysPatientFollow.setFollowTime(DateUtil.offsetMonth(preDate, 1));
            }
            list.add(sysPatientFollow);
            preDate = sysPatientFollow.getFollowTime();
        }
    }

    @Override
    public PageInfo<PatientFollowVo> listPage(PageParam<SysPatientFollow> param, String openId) {
        // 先根据openId查询护士信息
        SysNurse sysNurse = sysNurseService.selectByOpenId(openId);
        if (sysNurse == null) {
            throw new BusinessException("请先前往患者管理页面进行护士信息的认证");
        }
        // 查询护士所属的范围
        SysRangeNurse sysRangeNurse = sysRangeNurseService.selectByNurseId(sysNurse.getId());
        if (sysRangeNurse == null) {
            throw new BusinessException("请联系后台管理员设置您的所属范围");
        }
        // 查询范围所关联的医院信息
        List<SysRangeHospital> sysRangeHospitalList = sysRangeHospitalService.selectByRangeIds(Collections.singletonList(sysRangeNurse.getRangeId()));
        List<String> hospitalIds = sysRangeHospitalList.stream().map(SysRangeHospital::getHospitalId).collect(Collectors.toList());
        // 根据医院id查询已经入组的患者信息
        List<SysPatient> patients = sysPatientService.selectByHospitalIds(hospitalIds);
        if (CollectionUtils.isEmpty(patients)) {
            throw new BusinessException("您的名下没有待随访的患者信息");
        }
        List<String> patientIds = patients.stream().map(BaseEntity::getId).collect(Collectors.toList());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<PatientFollowVo> sysPatientFollows = sysPatientFollowMapper.listPage(patientIds, param.getParam());
        return new PageInfo<>(sysPatientFollows);
    }

    @Override
    public PageInfo<PatientFollowVo> currentMonthListPage(PageParam<SysPatientFollow> param, String openId) {
        // 先根据openId查询护士信息
        SysNurse sysNurse = sysNurseService.selectByOpenId(openId);
        if (sysNurse == null) {
            throw new BusinessException("请先前往患者管理页面进行护士信息的认证");
        }
        // 查询护士所属的范围
        SysRangeNurse sysRangeNurse = sysRangeNurseService.selectByNurseId(sysNurse.getId());
        if (sysRangeNurse == null) {
            throw new BusinessException("请联系后台管理员设置您的所属范围");
        }
        // 查询范围所关联的医院信息
        List<SysRangeHospital> sysRangeHospitalList = sysRangeHospitalService.selectByRangeIds(Collections.singletonList(sysRangeNurse.getRangeId()));
        List<String> hospitalIds = sysRangeHospitalList.stream().map(SysRangeHospital::getHospitalId).collect(Collectors.toList());
        // 根据医院id查询已经入组的患者信息
        List<SysPatient> patients = sysPatientService.selectByHospitalIds(hospitalIds);
        List<String> patientIds = patients.stream().map(BaseEntity::getId).collect(Collectors.toList());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<PatientFollowVo> sysPatientFollows = sysPatientFollowMapper.currentMonthListPage(patientIds, DateUtil.beginOfMonth(new Date()), DateUtil.endOfMonth(new Date()));
        return new PageInfo<>(sysPatientFollows);
    }

    @Override
    public List<PatientFollowVo> listPageByPatientId(SysPatientFollow sysPatientFollow) {
        if (StringUtils.isEmpty(sysPatientFollow.getPatientId())) {
            throw new BusinessException("患者id不能为空");
        }
        if (sysPatientFollow.getType() == null) {
            throw new BusinessException("类型不能为空");
        }
        return sysPatientFollowMapper.listPageByPatientId(sysPatientFollow);
    }

    @Override
    @Transactional
    public int deletePatientFollow(String id, String userId, String userName) {
        SysPatientFollow patientFollow = sysPatientFollowMapper.selectByPrimaryKey(id);
        if (patientFollow == null) {
            throw new BusinessException("随访记录不存在");
        }
        patientFollow.setUpdateBy(userId);
        patientFollow.setUpdater(userName);
        patientFollow.setDelFlag(Constants.DELETE_YES);
        patientFollow.setUpdateDate(new Date());
        return sysPatientFollowMapper.updateByPrimaryKeySelective(patientFollow);
    }

    @Override
    @Transactional
    public void addPatientFollowLog(SysPatientFollow sysPatientFollow) {
        SysPatient patient = sysPatientService.selectByKey(sysPatientFollow.getPatientId());
        if (patient == null) {
            throw new BusinessException("患者信息不存在");
        }
        if (!Constants.YES.equals(patient.getAuditStatus())) {
            throw new BusinessException("非在组患者不能进行随访");
        }

        // 校验日期是否已经存在
        SysPatientFollow query = new SysPatientFollow();
        query.setPatientId(sysPatientFollow.getPatientId());
        query.setFollowTime(sysPatientFollow.getFollowTime());
        query.setType(Constants.NO);
        query.setDelFlag(Constants.DELETE_NO);

        SysPatientFollow follow = sysPatientFollowMapper.selectOne(query);
        if (follow != null) {
            throw new BusinessException("随访日期不能重复");
        }
        SysPatientFollow lastFollow = sysPatientFollowMapper.queryLastFollow(sysPatientFollow.getPatientId());
        if (lastFollow == null) {
            throw new BusinessException("最近一条已经随访过的记录不存在");
        }
        LocalDateTime followTime = DateUtil.parseLocalDateTime(DateUtil.format(sysPatientFollow.getFollowTime(), "yyyy-MM-dd HH:mm:ss"));
        LocalDateTime lastFollowTime = DateUtil.parseLocalDateTime(DateUtil.format(lastFollow.getFollowTime(), "yyyy-MM-dd HH:mm:ss"));
        if (followTime.isBefore(lastFollowTime)) {
            throw new BusinessException("不能新增历史随访记录");
        }
        sysPatientFollow.setNurseId(patient.getNurseId());
        sysPatientFollow.setPatientName(patient.getRealName());
        sysPatientFollow.setPrescription(patient.getPrescription());
        sysPatientFollow.setChangeReason(patient.getChangeReason());
        sysPatientFollow.setJoinTime(patient.getJoinTime());
        sysPatientFollow.setId(SnowFlakeUtil.getStringId());
        String uuid = sysGeneratorCodeService.fetchUUID(RedisKeyPrefix.PATIENT_FOLLOW_KEY, 6, false);
        sysPatientFollow.setFollowCode("PF" + uuid);
        sysPatientFollow.setType(Constants.NO);
        sysPatientFollow.setHospitalId(patient.getHospitalId());
        sysPatientFollow.setNurseId(patient.getNurseId());
        List<SysHospital> sysHospitals = sysHospitalService.selectByIds(Collections.singletonList(patient.getHospitalId()));
        Optional<SysHospital> first = sysHospitals.stream().findFirst();
        if(first.isPresent()){
            SysHospital sysHospital = first.get();
            sysPatientFollow.setHospitalId(patient.getHospitalId());
            sysPatientFollow.setHospitalType(sysHospital.getHospitalType());
            sysPatientFollow.setJoinProvinceId(sysHospital.getProvinceCode());
            sysPatientFollow.setJoinCityId(sysHospital.getCityCode());
            sysPatientFollow.setRegion(sysHospital.getRegion());
            sysPatientFollow.setBigRegion(sysHospital.getBigRegion());
            sysPatientFollow.setRangeId(sysHospital.getRangeId());
        }
        sysPatientFollowMapper.insertSelective(sysPatientFollow);
    }

    @Override
    public List<EveryDayFollowNumber> queryEveryDayFollowNumber(String openid, Date followTime) {
        if (followTime == null) {
            throw new BusinessException("随访日期不能为空");
        }
        // 先根据openId查询护士信息
        SysNurse sysNurse = sysNurseService.selectByOpenId(openid);
        if (sysNurse == null) {
            throw new BusinessException("请先前往患者管理页面进行护士信息的认证");
        }
        // 查询护士所属的范围
        SysRangeNurse sysRangeNurse = sysRangeNurseService.selectByNurseId(sysNurse.getId());
        if (sysRangeNurse == null) {
            throw new BusinessException("请联系后台管理员设置您的所属范围");
        }
        // 查询范围所关联的医院信息
        List<SysRangeHospital> sysRangeHospitalList = sysRangeHospitalService.selectByRangeIds(Collections.singletonList(sysRangeNurse.getRangeId()));
        List<String> hospitalIds = sysRangeHospitalList.stream().map(SysRangeHospital::getHospitalId).collect(Collectors.toList());
        // 根据医院id查询已经入组的患者信息
        List<SysPatient> patients = sysPatientService.selectByHospitalIds(hospitalIds);
        List<String> patientIds = patients.stream().map(BaseEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(patientIds)) {
            throw new BusinessException("您的名下没有患者存在");
        }
        return sysPatientFollowMapper.queryEveryDayFollowNumber(patientIds, DateUtil.beginOfMonth(followTime), DateUtil.endOfMonth(followTime));
    }


    @Override
    public String queryNextFollowTimeByPatientId(String patientId) {
        return sysPatientFollowMapper.queryNextFollowTimeByPatientId(patientId);
    }

    @Override
    public Long queryCurrentDayFollowCount(List<String> patientIds) {
        if (CollectionUtils.isEmpty(patientIds)) {
            return 0L;
        }
        return sysPatientFollowMapper.queryCurrentDayFollowCount(patientIds);
    }

    @Override
    @Transactional
    public int updateFollow(SysPatientFollow sysPatientFollow) {
        if (StringUtils.isEmpty(sysPatientFollow.getContent())) {
            throw new BusinessException("随访内容不能为空");
        }
        if (StringUtils.isEmpty(sysPatientFollow.getId())) {
            throw new BusinessException("id不能为空");
        }

        SysPatientFollow follow = sysPatientFollowMapper.selectByPrimaryKey(sysPatientFollow.getId());
        if (follow == null) {
            throw new BusinessException("id不合法");
        }
        if (Constants.YES.equals(follow.getStatus())) {
            throw new BusinessException("已经随访过的记录不能再次编辑");
        }
        SysPatient patient = sysPatientService.selectByKey(follow.getPatientId());
        if (patient == null) {
            throw new BusinessException("患者信息不存在");
        }
        if (Constants.TWO.equals(patient.getAuditStatus())) {
            throw new BusinessException("已经脱组的用户不能进行随访");
        }
        SysNurse sysNurse = sysNurseService.selectByOpenId(sysPatientFollow.getUpdateBy());
        if (sysNurse == null) {
            throw new BusinessException("您的护士信息不存在");
        }
        if (!patient.getNurseId().equals(sysNurse.getId())) {
            throw new BusinessException("该患者已经与同范围的其他护士绑定，您不能对此患者进行随访");
        }
        List<PatientFollowVo> patientFollowVos = sysPatientFollowMapper.listByPatientId(follow.getPatientId());
        Optional<PatientFollowVo> first = patientFollowVos.stream().filter(f -> f.getId().equals(sysPatientFollow.getId())).findFirst();
        if (!first.isPresent()) {
            throw new BusinessException("id不合法");
        }
        PatientFollowVo patientFollowVo = first.get();
        Optional<PatientFollowVo> preOptional = patientFollowVos.stream().filter(f -> f.getRowNumber().equals(patientFollowVo.getRowNumber() - 1)).findFirst();
        if (!preOptional.isPresent()) {
            throw new BusinessException("上一条随访记录不存在");
        }
        PatientFollowVo prePatientFollow = preOptional.get();
        if (Constants.NO.equals(prePatientFollow.getStatus())) {
            throw new BusinessException("不能越级随访，请先选择上一条记录进行随访");
        }
        sysPatientFollow.setStatus(Constants.YES);

        String content = sysPatientFollow.getContent();
        JSONObject jsonObject = JSON.parseObject(content);
        resolvingFollowData(patient, jsonObject);
        patient.setFollowCount(patient.getFollowCount() + 1);
        patient.setUpdateDate(new Date());
        sysPatientService.update(patient);

        sysPatientFollow.setPatientName(patient.getRealName());
        sysPatientFollow.setPrescription(patient.getPrescription());
        sysPatientFollow.setChangeReason(patient.getChangeReason());
        sysPatientFollow.setJoinTime(patient.getJoinTime());
        sysPatientFollow.setNurseId(patient.getNurseId());
        List<SysHospital> sysHospitals = sysHospitalService.selectByIds(Collections.singletonList(patient.getHospitalId()));
        Optional<SysHospital> firstOption = sysHospitals.stream().findFirst();
        if(firstOption.isPresent()){
            SysHospital sysHospital = firstOption.get();
            sysPatientFollow.setHospitalId(patient.getHospitalId());
            sysPatientFollow.setHospitalType(sysHospital.getHospitalType());
            sysPatientFollow.setJoinProvinceId(sysHospital.getProvinceCode());
            sysPatientFollow.setJoinCityId(sysHospital.getCityCode());
            sysPatientFollow.setRegion(sysHospital.getRegion());
            sysPatientFollow.setBigRegion(sysHospital.getBigRegion());
            sysPatientFollow.setRangeId(sysHospital.getRangeId());
        }

        return sysPatientFollowMapper.updateByPrimaryKeySelective(sysPatientFollow);
    }

    private void resolvingFollowData(SysPatient sysPatient, JSONObject jsonObject) {
        // 从json字符串中解析患者是否是已处方患者
        String isPrescription = jsonObject.getString("question4");
        JSONObject prescriptionData = JSON.parseObject(isPrescription);

        // 更新处方状态
        if (Constants.YES_STRING.equals(prescriptionData.getString("val"))) {
            sysPatient.setPrescription(Constants.YES);
            sysPatient.setPrescriptionNumber(sysPatient.getPrescriptionNumber() + 1);
            sysPatient.setPrescriptionTime(new Date());
            sysPatient.setCurrentTreatmentBrand("安佳因");
        } else {
            sysPatient.setPrescription(Constants.NO);
        }

        // 处方原因
        String changeReason = jsonObject.getString("question4.3");
        JSONObject changeReasonData = JSON.parseObject(changeReason);
        sysPatient.setChangeReason(changeReasonData.getString("val"));

        // 转诊医院
        String changeHospital = jsonObject.getString("question7");
        JSONObject changeHospitalObj = JSON.parseObject(changeHospital);
        String patientChangeHospital = changeHospitalObj.getString("val");
        if (Constants.YES_STRING.equals(patientChangeHospital)) {
            // 转诊省份和城市
            String addressJson = jsonObject.getString("question7.1");
            JSONObject addressObj = JSON.parseObject(addressJson);
            String address = addressObj.getString("id");
            if (!StringUtils.isEmpty(address)) {
                String[] addressSplit = address.split("_");
                sysPatient.setJoinProvinceId(addressSplit[0]);
                sysPatient.setJoinCityId(addressSplit[1]);
            }

            String hospital = jsonObject.getString("question7.2");
            JSONObject hospitalObj = JSON.parseObject(hospital);
            String hospitalId = hospitalObj.getString("id");
            sysPatient.setHospitalId(hospitalId);
            // 查询这个医院所对应的护士信息
            SysRangeHospital sysRangeHospital = sysRangeHospitalService.selectByHospitalId(hospitalId);
            if (sysRangeHospital == null) {
                throw new BusinessException("转诊的医院没有绑定对应的所属范围");
            }
            List<SysRangeNurse> sysRangeNurses = sysRangeNurseService.selectByRangeIds(Collections.singletonList(sysRangeHospital.getRangeId()));
            Optional<SysRangeNurse> firstNurse = sysRangeNurses.stream().findFirst();
            firstNurse.ifPresent(sysRangeNurse -> sysPatient.setNurseId(sysRangeNurse.getNurseId()));
        }

        String status = jsonObject.getString("question12");
        JSONObject statusObj = JSON.parseObject(status);
        String patientStatus = statusObj.getString("val");
        if (PatientStatusEnum.IN_GROUP.getDesc().equals(patientStatus)) {
            sysPatient.setAuditStatus(PatientStatusEnum.IN_GROUP.getKey());
        } else if (PatientStatusEnum.LEAVE_GROUP.getDesc().equals(patientStatus)) {
            String exitReason = jsonObject.getString("question12.1");
            JSONObject reasonObj = JSON.parseObject(exitReason);
            String reason = reasonObj.getString("val");
            sysPatient.setRemarks(reason);
            sysPatient.setAuditStatus(PatientStatusEnum.LEAVE_GROUP.getKey());
            sysPatient.setExitTime(new Date());
            // 如果是脱组需要将之后的随访记录都删除
            sysPatientFollowMapper.deleteInvalidFollows(sysPatient.getId());
        } else if (PatientStatusEnum.LOST_CONTACT.getDesc().equals(patientStatus)) {
            int flag = 0;
            List<SysPatientFollow> sysPatientFollows = sysPatientFollowService.getLastTwoFollow(sysPatient.getId());
            for (SysPatientFollow patientFollow : sysPatientFollows) {
                String followContent = patientFollow.getContent();
                if (Constants.YES.equals(patientFollow.getSerialNumber())) {
                    JSONObject parseObject = JSONObject.parseObject(followContent);
                    String state = parseObject.getString("question25");
                    JSONObject stateObj = JSON.parseObject(state);
                    String patientState = stateObj.getString("val");
                    if (PatientStatusEnum.LOST_CONTACT.getDesc().equals(patientState)) {
                        flag++;
                    }
                } else {
                    JSONObject parseObject = JSONObject.parseObject(followContent);
                    String state = parseObject.getString("question12");
                    JSONObject stateObj = JSON.parseObject(state);
                    String patientState = stateObj.getString("val");
                    if (PatientStatusEnum.LOST_CONTACT.getDesc().equals(patientState)) {
                        flag++;
                    }
                }
            }
            if (flag == 2) {
                sysPatient.setRemarks("连续三次失联记为脱组");
                sysPatient.setExitTime(new Date());
                sysPatient.setAuditStatus(Constants.TWO);
            }
        }

        // 当前治疗方案
        String treatmentPlansJson = jsonObject.getString("question1");
        JSONObject treatmentPlanData = JSON.parseObject(treatmentPlansJson);
        String planDataString = treatmentPlanData.getString("text");
        sysPatient.setTreatmentPlan(TreatmentPlanEnum.getKey(planDataString));

        // 目前治疗剂量
        String dosageJson = jsonObject.getString("question2");
        JSONObject dosageData = JSON.parseObject(dosageJson);
        if (StringUtils.hasText(dosageData.getString("val"))) {
            sysPatient.setDosage(dosageData.getString("val"));
        }

        // 用药频次
        String dosageFrequencyJson = jsonObject.getString("question2");
        JSONObject dosageFrequencyData = JSON.parseObject(dosageFrequencyJson);
        if (StringUtils.hasText(dosageFrequencyData.getString("val2"))) {
            sysPatient.setDosageFrequency(dosageFrequencyData.getString("val2"));
        }

        // 身高
        String heightAndWeightJson = jsonObject.getString("question3");
        JSONObject heightAndWeightData = JSON.parseObject(heightAndWeightJson);
        if (StringUtils.hasText(heightAndWeightData.getString("height"))) {
            sysPatient.setHeight(new BigDecimal(heightAndWeightData.getString("height")));
        }
        // 体重
        if (StringUtils.hasText(heightAndWeightData.getString("weight"))) {
            sysPatient.setWeight(new BigDecimal(heightAndWeightData.getString("weight")));
        }

        // 用药时间
        String medicationTimeJson = jsonObject.getString("question4.2");
        if (!StringUtils.isEmpty(medicationTimeJson)) {
            JSONObject medicationTimeData = JSON.parseObject(medicationTimeJson);
            sysPatient.setStartTreatmentTime(medicationTimeData.getString("startTreatmentTime"));
        }

        // 用药状态
        String medicationStatusJson = jsonObject.getString("question4.1");
        if (!StringUtils.isEmpty(medicationTimeJson)) {
            JSONObject medicationStatusData = JSON.parseObject(medicationStatusJson);
            sysPatient.setMedicationStatus(medicationStatusData.getString("val"));
        }

        // 是否申请援助
        String applyForAssistanceFlagJson = jsonObject.getString("question4.4");
        JSONObject applyForAssistanceFlagData = JSON.parseObject(applyForAssistanceFlagJson);
        String joinSupport = applyForAssistanceFlagData.getString("joinSupport");
        if (!StringUtils.isEmpty(joinSupport)) {
            sysPatient.setJoinSupport("是".equals(joinSupport) ? 1 : 0);
        }

    }

    @Override
    public int addPatientInquiry(SysPatientFollow sysPatientFollow) {
        SysPatient patient = sysPatientService.selectByKey(sysPatientFollow.getPatientId());
        if (patient == null) {
            throw new BusinessException("患者信息不存在");
        }
        if (!Constants.YES.equals(patient.getAuditStatus())) {
            throw new BusinessException("非在组患者不能进行问询");
        }
        sysPatientFollow.setPatientName(patient.getRealName());
        sysPatientFollow.setPrescription(patient.getPrescription());
        sysPatientFollow.setChangeReason(patient.getChangeReason());
        sysPatientFollow.setJoinTime(patient.getJoinTime());
        sysPatientFollow.setNurseId(patient.getNurseId());
        sysPatientFollow.setId(SnowFlakeUtil.getStringId());
        String uuid = sysGeneratorCodeService.fetchUUID(RedisKeyPrefix.PATIENT_INQUIRY_KEY, 6, false);
        sysPatientFollow.setFollowCode("AF" + uuid);
        sysPatientFollow.setType(Constants.YES);
        sysPatientFollow.setFollowTime(new Date());
        sysPatientFollow.setStatus(Constants.YES);
        List<SysHospital> sysHospitals = sysHospitalService.selectByIds(Collections.singletonList(patient.getHospitalId()));
        Optional<SysHospital> first = sysHospitals.stream().findFirst();
        if(first.isPresent()){
            SysHospital sysHospital = first.get();
            sysPatientFollow.setHospitalId(patient.getHospitalId());
            sysPatientFollow.setHospitalType(sysHospital.getHospitalType());
            sysPatientFollow.setJoinProvinceId(sysHospital.getProvinceCode());
            sysPatientFollow.setJoinCityId(sysHospital.getCityCode());
            sysPatientFollow.setRegion(sysHospital.getRegion());
            sysPatientFollow.setBigRegion(sysHospital.getBigRegion());
            sysPatientFollow.setRangeId(sysHospital.getRangeId());
        }
        return sysPatientFollowMapper.insertSelective(sysPatientFollow);
    }

    @Override
    public void remind() {
        List<SysPatientFollow> patientFollows = sysPatientFollowMapper.selectRemind();
        for (SysPatientFollow patientFollow : patientFollows) {
            logger.info("Send SMS Reminder nursePhone={},patientName={},follow_time={}", patientFollow.getNursePhone(),
                    patientFollow.getPatientName(), DateUtil.format(patientFollow.getFollowTime(), "yyyy-MM-dd"));
            sysSmsClient.sendSms(new String[]{"+86" + patientFollow.getNursePhone()}, SmsTemplateEnum.TEMPLATE_3.getKey(), new String[]{patientFollow.getPatientName(), DateUtil.format(patientFollow.getFollowTime(), "yyyy-MM-dd")});
            patientFollow.setRemindNumber(patientFollow.getRemindNumber() + 1);
            sysPatientFollowMapper.updateByPrimaryKeySelective(patientFollow);
        }
    }

    @Override
    public List<PatientFollowVo> listAllPage(SysPatientFollowDto pageParam) {
        List<PatientFollowVo> patientFollowVos = sysPatientFollowMapper.listAllPage(pageParam);
        if (!CollectionUtils.isEmpty(patientFollowVos)) {
            List<String> patientIds = patientFollowVos.stream().map(PatientFollowVo::getPatientId).distinct().collect(Collectors.toList());
            List<SysPatient> sysPatients = sysPatientService.selectByIds(patientIds);
            Map<String, SysPatient> sysPatientMap = sysPatients.stream().collect(Collectors.toMap(SysPatient::getId, f -> f));

            List<String> nurseIds = patientFollowVos.stream().map(PatientFollowVo::getNurseId).distinct().collect(Collectors.toList());
            List<SysNurse> sysNurses = sysNurseService.selectByIds(nurseIds);
            Map<String, SysNurse> sysNurseMap = sysNurses.stream().collect(Collectors.toMap(SysNurse::getId, f -> f));

            List<String> rangeIds = patientFollowVos.stream().map(PatientFollowVo::getRangeId).distinct().collect(Collectors.toList());
            List<SysRange> rangeList = sysRangeService.selectByIds(rangeIds);
            Map<String, SysRange> rangeMap = rangeList.stream().collect(Collectors.toMap(SysRange::getId, f -> f));

            for (PatientFollowVo patientFollowVo : patientFollowVos) {
                SysPatient sysPatient = sysPatientMap.get(patientFollowVo.getPatientId());
                if(Objects.nonNull(sysPatient)){
                    patientFollowVo.setPhone(sysPatient.getPhone());
                    patientFollowVo.setIcfCode(sysPatient.getFollowCode());
                    if(PatientStatusEnum.LEAVE_GROUP.getKey() == sysPatient.getAuditStatus()){
                        patientFollowVo.setExitTime(sysPatient.getExitTime());
                    }
                }

                SysNurse sysNurse = sysNurseMap.get(patientFollowVo.getNurseId());
                if(Objects.nonNull(sysNurse)){
                    patientFollowVo.setNurseName(sysNurse.getRealName());
                }

                SysRange sysRange = rangeMap.get(patientFollowVo.getRangeId());
                if(Objects.nonNull(sysRange)){
                    patientFollowVo.setRangeName(sysRange.getRangeName());
                }
            }
        }
        return patientFollowVos;
    }

    @Override
    public List<PatientFollowDetailVo> listAllDetail(SysPatientFollowDto sysPatientFollow) {
        List<PatientFollowDetailVo> patientFollowVos = sysPatientFollowMapper.listAllDetail(sysPatientFollow);

        if (!CollectionUtils.isEmpty(patientFollowVos)) {
            // 查询地址信息
            List<SysAddress> sysAddresses = sysAddressService.getAll();
            Map<String, String> addRessMap = sysAddresses.stream().collect(Collectors.toMap(SysAddress::getCode, SysAddress::getName));

            List<String> patientIds = patientFollowVos.stream().map(PatientFollowDetailVo::getPatientId).distinct().collect(Collectors.toList());
            List<SysPatient> sysPatients = sysPatientService.selectByIds(patientIds);
            Map<String, SysPatient> sysPatientMap = sysPatients.stream().collect(Collectors.toMap(SysPatient::getId, f -> f));

            List<String> nurseIds = patientFollowVos.stream().map(PatientFollowDetailVo::getNurseId).distinct().collect(Collectors.toList());
            List<SysNurse> sysNurses = sysNurseService.selectByIds(nurseIds);
            Map<String, SysNurse> sysNurseMap = sysNurses.stream().collect(Collectors.toMap(SysNurse::getId, f -> f));

            List<String> rangeIds = patientFollowVos.stream().map(PatientFollowDetailVo::getRangeId).distinct().collect(Collectors.toList());
            List<SysRange> rangeList = sysRangeService.selectByIds(rangeIds);
            Map<String, SysRange> rangeMap = rangeList.stream().collect(Collectors.toMap(SysRange::getId, f -> f));

            // 查询协议签署
            List<SysAgreement> agreementList = sysAgreementService.batchQueryByPatientIds(patientIds, 1);
            Map<String, Date> agreementMap = agreementList.stream().collect(Collectors.toMap(SysAgreement::getUserId, SysAgreement::getSignTime));

            List<String> hospitalIds = patientFollowVos.stream().map(PatientFollowDetailVo::getHospitalId).distinct().collect(Collectors.toList());
            List<SysHospital> sysHospitals = sysHospitalService.selectByIds(hospitalIds);
            Map<String, SysHospital> hospitalMap = sysHospitals.stream().collect(Collectors.toMap(SysHospital::getId, f -> f));

            for (PatientFollowDetailVo patientFollowDetailVo : patientFollowVos) {
                patientFollowDetailVo.setJoinCityName(addRessMap.get(patientFollowDetailVo.getJoinCityId()));
                patientFollowDetailVo.setSignTime(agreementMap.get(patientFollowDetailVo.getPatientId()));
                if (Constants.YES.equals(patientFollowDetailVo.getStatus())) {
                    String jsonData = patientFollowDetailVo.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (Constants.YES.equals(patientFollowDetailVo.getSerialNumber())) {
                        resolvingFollowJsonData(patientFollowDetailVo, jsonObject);
                    } else {
                        try {
                            resolvingFollowJsonData1(patientFollowDetailVo, jsonObject);
                        } catch (Exception e) {
                            resolvingFollowJsonData(patientFollowDetailVo, jsonObject);
                        }
                    }
                }
                SysPatient sysPatient = sysPatientMap.get(patientFollowDetailVo.getPatientId());
                if(Objects.nonNull(sysPatient)){
                    patientFollowDetailVo.setPatientPhone(sysPatient.getPhone());
                    patientFollowDetailVo.setIcfCode(sysPatient.getFollowCode());
                    if(sysPatient.getSex() == 0){
                        patientFollowDetailVo.setSex("未知");
                    }else if(sysPatient.getPatientType() == 1){
                        patientFollowDetailVo.setSex("男");
                    }else if(sysPatient.getPatientType() == 2){
                        patientFollowDetailVo.setSex("女");
                    }else{
                        patientFollowDetailVo.setSex("未知");
                    }
                    patientFollowDetailVo.setWeight(sysPatient.getWeight());
                    patientFollowDetailVo.setHeight(sysPatient.getHeight());
                    patientFollowDetailVo.setAge(sysPatient.getAge());
                    patientFollowDetailVo.setIdNum(sysPatient.getIdNum());
                    patientFollowDetailVo.setJoinCode(sysPatient.getJoinCode());
                    if(sysPatient.getPatientType() == 0){
                        patientFollowDetailVo.setAgeStage("成年");
                    }else if(sysPatient.getPatientType() == 1){
                        patientFollowDetailVo.setAgeStage("青少年");
                    }else if(sysPatient.getPatientType() == 2){
                        patientFollowDetailVo.setAgeStage("其他（12岁以下）");
                    }else{
                        patientFollowDetailVo.setAgeStage("未知");
                    }
                }

                SysNurse sysNurse = sysNurseMap.get(patientFollowDetailVo.getNurseId());
                if(Objects.nonNull(sysNurse)){
                    patientFollowDetailVo.setNurseName(sysNurse.getRealName());
                }

                SysRange sysRange = rangeMap.get(patientFollowDetailVo.getRangeId());
                if(Objects.nonNull(sysRange)){
                    patientFollowDetailVo.setRangeName(sysRange.getRangeName());
                }
                SysHospital sysHospital = hospitalMap.get(patientFollowDetailVo.getHospitalId());
                if(Objects.nonNull(sysHospital)){
                    patientFollowDetailVo.setHospitalName(sysHospital.getHospitalName());
                }
            }
        }
        return patientFollowVos;
    }


    @Override
    public List<PatientFollowDetailVo> multiThreadQueryDetail(SysPatientFollowDto sysPatientFollow) throws Exception {
        long startTime = System.currentTimeMillis();
        List<PatientFollowDetailVo> list = new ArrayList<>();
        int count = sysPatientFollowMapper.count(sysPatientFollow);
        // 自定义每次查询的行数
        int rows = 10000;
        // 计算遍历的次数
        int allPage = (count - 1) / rows + 1;
        logger.info("开始查询-->");
        int offset = 0;
        List<Callable<List<PatientFollowDetailVo>>> taskList = Lists.newArrayList();
        // 创建任务
        for (int i = 0; i < allPage; i++) {
            Callable<List<PatientFollowDetailVo>> task = new TaskThreadQuery(sysPatientFollowMapper, sysPatientFollow, offset, rows);
            taskList.add(task);
            offset += rows;
        }
        // 可自定义线程数量
        int threadNum = 10;
        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        List<Future<List<PatientFollowDetailVo>>> futureList = executor.invokeAll(taskList);
        logger.info("size = {}", futureList.size());
        if (futureList.size() > 0) {
            for (Future<List<PatientFollowDetailVo>> future : futureList) {
                if (future.get() != null) {
                    list.addAll(future.get());
                }
            }
        }
        // 关闭线程
        executor.shutdown();
        long endTime = System.currentTimeMillis();
        long s = ((endTime - startTime) / 1000);
        logger.info(threadNum + "个线程查询花了" + s + "秒");
        return list;
    }

    @Override
    public List<PatientInquiryDetailVo> listInquiryDetail(SysPatientFollowDto sysPatientFollow) {
        List<PatientInquiryDetailVo> patientFollowDetailVos = sysPatientFollowMapper.listInquiryDetail(sysPatientFollow);

        if (!CollectionUtils.isEmpty(patientFollowDetailVos)) {
            List<SysAddress> sysAddresses = sysAddressService.getAll();
            Map<String, String> addRessMap = sysAddresses.stream().collect(Collectors.toMap(SysAddress::getCode, SysAddress::getName));

            for (PatientInquiryDetailVo patientFollowDetailVo : patientFollowDetailVos) {
                if (Constants.YES.equals(patientFollowDetailVo.getStatus())) {
                    String jsonData = patientFollowDetailVo.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    resolvingInquiryJsonData(patientFollowDetailVo, jsonObject);
                }
                patientFollowDetailVo.setJoinCityName(addRessMap.get(patientFollowDetailVo.getJoinCityCode()));
            }
        }

        return patientFollowDetailVos;
    }

    private void resolvingFollowJsonData1(PatientFollowDetailVo patientFollowDetailVo, JSONObject jsonObject) {
        // 当前治疗方案
        String treatmentPlansJson = jsonObject.getString("question1");
        JSONObject treatmentPlanData = JSON.parseObject(treatmentPlansJson);
        String planDataString = treatmentPlanData.getString("text");
        if (!StringUtils.isEmpty(planDataString)) {
            patientFollowDetailVo.setTreatmentPlan(planDataString);
        } else {
            String planDataVal = treatmentPlanData.getString("val");
            if (!StringUtils.isEmpty(planDataVal)) {
                patientFollowDetailVo.setTreatmentPlan(TreatmentPlanEnum.getDesc(Integer.parseInt(planDataVal)));
            }
        }

        // 目前治疗剂量
        String dosageJson = jsonObject.getString("question2");
        JSONObject dosageData = JSON.parseObject(dosageJson);
        if (StringUtils.hasText(dosageData.getString("val"))) {
            patientFollowDetailVo.setDosage(dosageData.getString("val"));
        }

        // 用药频次
        String dosageFrequencyJson = jsonObject.getString("question2");
        JSONObject dosageFrequencyData = JSON.parseObject(dosageFrequencyJson);
        if (StringUtils.hasText(dosageFrequencyData.getString("val2"))) {
            patientFollowDetailVo.setDosageFrequency(dosageFrequencyData.getString("val2"));
        }

        // 身高
        String heightAndWeightJson = jsonObject.getString("question3");
        JSONObject heightAndWeightData = JSON.parseObject(heightAndWeightJson);
        if (StringUtils.hasText(heightAndWeightData.getString("height"))) {
            patientFollowDetailVo.setHeight(new BigDecimal(heightAndWeightData.getString("height")));
        }
        // 体重
        if (StringUtils.hasText(heightAndWeightData.getString("weight"))) {
            patientFollowDetailVo.setWeight(new BigDecimal(heightAndWeightData.getString("weight")));
        }

        // 目前是否使用安佳因
        String isAnjiainCurrentlyUsedJson = jsonObject.getString("question4");
        JSONObject isAnjiainCurrentlyUsedData = JSON.parseObject(isAnjiainCurrentlyUsedJson);
        patientFollowDetailVo.setIsAnjiainCurrentlyUsed(isAnjiainCurrentlyUsedData.getString("val"));

        // 用药时间
        String medicationTimeJson = jsonObject.getString("question4.2");
        if (!StringUtils.isEmpty(medicationTimeJson)) {
            JSONObject medicationTimeData = JSON.parseObject(medicationTimeJson);
            patientFollowDetailVo.setMedicationTime(medicationTimeData.getString("startTreatmentTime"));
        }

        // 用药状态
        String medicationStatusJson = jsonObject.getString("question4.1");
        if (!StringUtils.isEmpty(medicationTimeJson)) {
            JSONObject medicationStatusData = JSON.parseObject(medicationStatusJson);
            patientFollowDetailVo.setMedicationStatus(medicationStatusData.getString("val"));
        }

        // 处方原因
        String reasonForPrescriptionJson = jsonObject.getString("question4.3");
        JSONObject reasonForPrescriptionData = JSON.parseObject(reasonForPrescriptionJson);
        patientFollowDetailVo.setReasonForPrescription(reasonForPrescriptionData.getString("val"));

        // 是否申请援助
        String applyForAssistanceFlagJson = jsonObject.getString("question4.4");
        JSONObject applyForAssistanceFlagData = JSON.parseObject(applyForAssistanceFlagJson);
        patientFollowDetailVo.setApplyForAssistanceFlag(applyForAssistanceFlagData.getString("joinSupport"));

        // 是否收到物料包
        String receiveTheMaterialPackageFlagJson = jsonObject.getString("question5");
        JSONObject receiveTheMaterialPackageFlagData = JSON.parseObject(receiveTheMaterialPackageFlagJson);
        patientFollowDetailVo.setReceiveTheMaterialPackageFlag(receiveTheMaterialPackageFlagData.getString("val"));

        // 是否转诊
        String referralFlagJson = jsonObject.getString("question7");
        JSONObject referralFlagData = JSON.parseObject(referralFlagJson);
        patientFollowDetailVo.setReferralFlag(referralFlagData.getString("val"));

        // 转诊医院名称
        String referralHospitalNameJson = jsonObject.getString("question7.2");
        JSONObject referralHospitalNameData = JSON.parseObject(referralHospitalNameJson);
        patientFollowDetailVo.setReferralHospitalName(referralHospitalNameData.getString("val"));


        // 随访方式
        String followWayJson = jsonObject.getString("question11");
        JSONObject followWayData = JSON.parseObject(followWayJson);
        patientFollowDetailVo.setFollowWay(followWayData.getString("val"));

        // 受访状态
        String interviewStatusJson = jsonObject.getString("question12");
        JSONObject interviewStatusData = JSON.parseObject(interviewStatusJson);
        patientFollowDetailVo.setInterviewStatus(interviewStatusData.getString("val"));

        // 脱组原因
        String exitReasonJson = jsonObject.getString("question12.1");
        JSONObject exitReasonData = JSON.parseObject(exitReasonJson);
        patientFollowDetailVo.setExitReason(exitReasonData.getString("val"));

        // 是否AE
        String aeFlagJson = jsonObject.getString("question13");
        JSONObject aeFlagData = JSON.parseObject(aeFlagJson);
        patientFollowDetailVo.setAeFlag(aeFlagData.getString("val"));

    }

    private void resolvingFollowJsonData(PatientFollowDetailVo patientFollowDetailVo, JSONObject jsonObject) {
        // 性别
        String sexJson = jsonObject.getString("question3");
        JSONObject sexData = JSON.parseObject(sexJson);
        String val = sexData.getString("val");
        patientFollowDetailVo.setSex(val);
        // 年龄
        String ageJson = jsonObject.getString("question2");
        JSONObject ageData = JSON.parseObject(ageJson);
        patientFollowDetailVo.setAge(ageData.getString("val"));

        // 患者类型
        String userTypeJson = jsonObject.getString("question1");
        JSONObject userTypeData = JSON.parseObject(userTypeJson);
        patientFollowDetailVo.setAgeStage(StringUtils.isEmpty(userTypeData.getString("val")) ? "未知" : userTypeData.getString("val"));

        // 医保类型
        String medicalInsuranceJson = jsonObject.getString("question6");
        JSONObject medicalInsuranceData = JSON.parseObject(medicalInsuranceJson);
        patientFollowDetailVo.setMedicalInsurance(medicalInsuranceData.getString("val"));

        // 医保是否限额
        String medicalInsuranceLimitJson = jsonObject.getString("question7");
        JSONObject medicalInsuranceLimitData = JSON.parseObject(medicalInsuranceLimitJson);
        patientFollowDetailVo.setMedicalInsuranceLimit(medicalInsuranceLimitData.getString("val"));

        // 医保限额
        String medicalInsuranceLimitMoneyJson = jsonObject.getString("question7.1");
        JSONObject medicalInsuranceLimitMoneyData = JSON.parseObject(medicalInsuranceLimitMoneyJson);
        if (StringUtils.hasText(medicalInsuranceLimitMoneyData.getString("val"))) {
            patientFollowDetailVo.setMedicalInsuranceLimitMoney(new BigDecimal(medicalInsuranceLimitMoneyData.getString("val")));
        }

        // 是否转诊
        String referralFlagJson = jsonObject.getString("question33");
        JSONObject referralFlagData = JSON.parseObject(referralFlagJson);
        if (Objects.nonNull(referralFlagData)) {
            patientFollowDetailVo.setReferralFlag(referralFlagData.getString("val"));
        }

        // 转诊医院名称
        String referralHospitalNameJson = jsonObject.getString("question33.2");
        JSONObject referralHospitalNameData = JSON.parseObject(referralHospitalNameJson);
        if (Objects.nonNull(referralHospitalNameData)) {
            patientFollowDetailVo.setReferralHospitalName(referralHospitalNameData.getString("val"));
        }

        // 确诊时间
        String firstDiagnosisTimeJson = jsonObject.getString("question8");
        JSONObject firstDiagnosisTimeData = JSON.parseObject(firstDiagnosisTimeJson);
        if (Objects.nonNull(firstDiagnosisTimeData)) {
            patientFollowDetailVo.setFirstDiagnosisTime(firstDiagnosisTimeData.getString("val"));
        }

        // 首次治疗时间
        String startTreatmentTimeJson = jsonObject.getString("question9");
        JSONObject startTreatmentTimeData = JSON.parseObject(startTreatmentTimeJson);
        if (Objects.nonNull(startTreatmentTimeData)) {
            patientFollowDetailVo.setStartTreatmentTime(startTreatmentTimeData.getString("val"));
        }

        // 既往用药品牌
        String historyPharmacyJson = jsonObject.getString("question10.1");
        JSONObject historyPharmacyData = JSON.parseObject(historyPharmacyJson);
        if (Objects.nonNull(historyPharmacyData)) {
            patientFollowDetailVo.setHistoryPharmacy(historyPharmacyData.getString("val").replace("[", "").replace("]", ""));
        }

        // 身高
        String heightAndWeightJson = jsonObject.getString("question13");
        JSONObject heightAndWeightData = JSON.parseObject(heightAndWeightJson);
        if (StringUtils.hasText(heightAndWeightData.getString("height"))) {
            patientFollowDetailVo.setHeight(new BigDecimal(heightAndWeightData.getString("height")));
        }
        // 体重
        if (StringUtils.hasText(heightAndWeightData.getString("weight"))) {
            patientFollowDetailVo.setWeight(new BigDecimal(heightAndWeightData.getString("weight")));
        }

        // 目前治疗药物
        String currentTreatmentDrugsJson = jsonObject.getString("question10.1");
        JSONObject currentTreatmentDrugsData = JSON.parseObject(currentTreatmentDrugsJson);
        if (Objects.nonNull(currentTreatmentDrugsData)) {
            patientFollowDetailVo.setCurrentTreatmentDrugs(currentTreatmentDrugsData.getString("val").replace("[", "").replace("]", ""));
        }

        // 当前治疗方案
        String treatmentPlansJson = jsonObject.getString("question11");
        JSONObject treatmentPlanData = JSON.parseObject(treatmentPlansJson);
        String planDataString = treatmentPlanData.getString("text");
        if (!StringUtils.isEmpty(planDataString)) {
            patientFollowDetailVo.setTreatmentPlan(planDataString);
        } else {
            String planDataVal = treatmentPlanData.getString("val");
            if (!StringUtils.isEmpty(planDataVal)) {
                patientFollowDetailVo.setTreatmentPlan(TreatmentPlanEnum.getDesc(Integer.parseInt(planDataVal)));
            }
        }

        // 目前治疗剂量
        String dosageJson = jsonObject.getString("question12");
        JSONObject dosageData = JSON.parseObject(dosageJson);
        if (StringUtils.hasText(dosageData.getString("val"))) {
            patientFollowDetailVo.setDosage(dosageData.getString("val"));
        }

        // 用药频次
        String dosageFrequencyJson = jsonObject.getString("question12");
        JSONObject dosageFrequencyData = JSON.parseObject(dosageFrequencyJson);
        if (StringUtils.hasText(dosageFrequencyData.getString("val2"))) {
            patientFollowDetailVo.setDosageFrequency(dosageFrequencyData.getString("val2"));
        }

        // 目前是否使用安佳因
        String isAnjiainCurrentlyUsedJson = jsonObject.getString("question16");
        JSONObject isAnjiainCurrentlyUsedData = JSON.parseObject(isAnjiainCurrentlyUsedJson);
        patientFollowDetailVo.setIsAnjiainCurrentlyUsed(isAnjiainCurrentlyUsedData.getString("val"));

        // 用药时间
        String medicationTimeJson = jsonObject.getString("question16.2");
        JSONObject medicationTimeData = JSON.parseObject(medicationTimeJson);
        patientFollowDetailVo.setMedicationTime(medicationTimeData.getString("startTreatmentTime"));

        // 用药状态
        String medicationStatusJson = jsonObject.getString("question16.1");
        JSONObject medicationStatusData = JSON.parseObject(medicationStatusJson);
        patientFollowDetailVo.setMedicationStatus(medicationStatusData.getString("val"));

        // 处方原因
        String reasonForPrescriptionJson = jsonObject.getString("question16.3");
        JSONObject reasonForPrescriptionData = JSON.parseObject(reasonForPrescriptionJson);
        patientFollowDetailVo.setReasonForPrescription(reasonForPrescriptionData.getString("val"));

        // 是否申请援助
        String applyForAssistanceFlagJson = jsonObject.getString("question16.4");
        JSONObject applyForAssistanceFlagData = JSON.parseObject(applyForAssistanceFlagJson);
        patientFollowDetailVo.setApplyForAssistanceFlag(applyForAssistanceFlagData.getString("joinSupport"));

        // 当前医保额度
        String currentMedicalInsuranceLimitJson = jsonObject.getString("question7.1");
        JSONObject currentMedicalInsuranceLimitData = JSON.parseObject(currentMedicalInsuranceLimitJson);
        patientFollowDetailVo.setCurrentMedicalInsuranceLimit(currentMedicalInsuranceLimitData.getString("val"));

        // 是否收到物料包
        String receiveTheMaterialPackageFlagJson = jsonObject.getString("question21");
        JSONObject receiveTheMaterialPackageFlagData = JSON.parseObject(receiveTheMaterialPackageFlagJson);
        patientFollowDetailVo.setReceiveTheMaterialPackageFlag(receiveTheMaterialPackageFlagData.getString("val"));

        // 是否AE
        String aeFlagJson = jsonObject.getString("question28");
        JSONObject aeFlagData = JSON.parseObject(aeFlagJson);
        patientFollowDetailVo.setAeFlag(aeFlagData.getString("val"));

        // 通知患教会
        String notifyTheSufferingChurchJson = jsonObject.getString("question27");
        JSONObject notifyTheSufferingChurchData = JSON.parseObject(notifyTheSufferingChurchJson);
        patientFollowDetailVo.setNotifyTheSufferingChurch(notifyTheSufferingChurchData.getString("val"));

        // 受访状态
        String interviewStatusJson = jsonObject.getString("question25");
        JSONObject interviewStatusData = JSON.parseObject(interviewStatusJson);
        patientFollowDetailVo.setInterviewStatus(interviewStatusData.getString("val"));

        // 脱组原因
        String exitReasonJson = jsonObject.getString("question25.1");
        JSONObject exitReasonData = JSON.parseObject(exitReasonJson);
        patientFollowDetailVo.setExitReason(exitReasonData.getString("val"));

        // 随访方式
        String followWayJson = jsonObject.getString("question24");
        JSONObject followWayData = JSON.parseObject(followWayJson);
        patientFollowDetailVo.setFollowWay(followWayData.getString("val"));
    }


    private void resolvingInquiryJsonData(PatientInquiryDetailVo patientFollowDetailVo, JSONObject jsonObject) {
        // 问题
        String questionJson = jsonObject.getString("question6");
        JSONObject questionData = JSON.parseObject(questionJson);
        patientFollowDetailVo.setQuestion(questionData.getString("val"));
        // 答复
        String answerJson = jsonObject.getString("question7");
        JSONObject answerData = JSON.parseObject(answerJson);
        patientFollowDetailVo.setAnswer(answerData.getString("val"));
    }

    @Override
    public List<PatientFollowVo> listByPatientId(String patientId) {
        return sysPatientFollowMapper.listByPatientId(patientId);
    }


    @Override
    public List<PrescriptionStatisticsVo> exportPrescriptionStatistics(DayReportQueryParam dayReportQueryParam) {
        List<PrescriptionStatisticsVo> prescriptionStatisticsVos = sysPatientService.exportPrescriptionStatistics(dayReportQueryParam);
        if (!CollectionUtils.isEmpty(prescriptionStatisticsVos)) {
            List<SysAddress> sysAddresses = sysAddressService.getAll();
            Map<String, String> addRessMap = sysAddresses.stream().collect(Collectors.toMap(SysAddress::getCode, SysAddress::getName));
            for (PrescriptionStatisticsVo prescriptionStatisticsVo : prescriptionStatisticsVos) {
                prescriptionStatisticsVo.setJoinCityName(addRessMap.get(prescriptionStatisticsVo.getJoinCityId()));
                prescriptionStatisticsVo.setJoinProvinceName(addRessMap.get(prescriptionStatisticsVo.getJoinProvinceId()));
            }
        }
        return prescriptionStatisticsVos;
    }

    @Override
    public List<FollowStatistics> exportStatistics(DayReportQueryParam dayReportQueryParam) {
        List<FollowStatistics> followStatisticsList = sysPatientService.selectAllNurse();
        if (!CollectionUtils.isEmpty(followStatisticsList)) {
            // 随访总数统计
            List<FollowStatistics> totalFollowCounts = sysPatientFollowMapper.queryTotalFollowCount(dayReportQueryParam);
            Map<String, Integer> totalFollowCountMap = totalFollowCounts.stream().collect(Collectors.toMap(FollowStatistics::getOpenId, FollowStatistics::getTotalFollowCount));
            // 问询总数统计
            List<FollowStatistics> totalInquiryCounts = sysPatientFollowMapper.queryTotalInquiryCount(dayReportQueryParam);
            Map<String, Integer> totalInquiryCountMap = totalInquiryCounts.stream().collect(Collectors.toMap(FollowStatistics::getOpenId, FollowStatistics::getTotalInquiryCount));
            // 临时问询统计
            List<FollowStatistics> temporaryInquiryCounts = sysNotepadService.queryTemporaryInquiryCount(dayReportQueryParam);
            Map<String, Integer> temporaryInquiryCountMap = temporaryInquiryCounts.stream().collect(Collectors.toMap(FollowStatistics::getOpenId, FollowStatistics::getTotalTemporaryInquiryCount));
            for (FollowStatistics statistics : followStatisticsList) {
                statistics.setTotalFollowCount(totalFollowCountMap.get(statistics.getOpenId()) == null ? 0 : totalFollowCountMap.get(statistics.getOpenId()));
                statistics.setTotalInquiryCount(totalInquiryCountMap.get(statistics.getOpenId()) == null ? 0 : totalInquiryCountMap.get(statistics.getOpenId()));
                statistics.setTotalTemporaryInquiryCount(temporaryInquiryCountMap.get(statistics.getOpenId()) == null ? 0 : temporaryInquiryCountMap.get(statistics.getOpenId()));
            }
        }
        return followStatisticsList;
    }

    @Override
    public List<SysPatientFollow> getLastTwoFollow(String patientId) {
        return sysPatientFollowMapper.getLastTwoFollow(patientId);
    }

    @Override
    public int updateInfo(SysPatientFollow sysPatientFollow) {
        SysPatientFollow follow = sysPatientFollowMapper.selectByPrimaryKey(sysPatientFollow.getId());
        if (follow == null) {
            throw new BusinessException("无效的参数");
        }
        if (Constants.NO.equals(follow.getType())) {
            String content = sysPatientFollow.getContent();
            JSONObject jsonObject = JSON.parseObject(content);
            if (Constants.YES.equals(follow.getSerialNumber())) {
                String followTimeJson = jsonObject.getString("question23");
                JSONObject followTimeData = JSON.parseObject(followTimeJson);
                String val = followTimeData.getString("val");
                if (!StringUtils.isEmpty(val)) {
                    sysPatientFollow.setFollowTime(DateUtil.parse(val, "yyyy-MM-dd"));
                }
            } else {
                String followTimeJson = jsonObject.getString("question10");
                JSONObject followTimeData = JSON.parseObject(followTimeJson);
                String val = followTimeData.getString("val");
                if (!StringUtils.isEmpty(val)) {
                    sysPatientFollow.setFollowTime(DateUtil.parse(val));
                }
            }
        }
        return sysPatientFollowMapper.updateByPrimaryKeySelective(sysPatientFollow);
    }

//    @Override
//    public void refresh() {
//        List<SysPatientFollow> sysPatientFollows = sysPatientFollowMapper.selectAll();
//        List<SysPatientFollow> collect = sysPatientFollows.stream().filter(f -> f.getDelFlag().equals("0") && Constants.NO.equals(f.getType()) && Constants.YES.equals(f.getStatus())).collect(Collectors.toList());
//        Map<String, List<SysPatientFollow>> map = collect.stream().collect(Collectors.groupingBy(SysPatientFollow::getPatientId));
//        for (Map.Entry<String, List<SysPatientFollow>> entry : map.entrySet()) {
//            String patientId = entry.getKey();
//            SysPatient sysPatient = sysPatientService.getPatientInfoById(patientId);
//            sysPatient.setFollowCount(entry.getValue().size());
//            sysPatientService.update(sysPatient);
//        }
//        List<SysHospital> sysHospitals = sysHospitalService.selectAll();
//        Map<String, SysHospital> hospitalMap = sysHospitals.stream().collect(Collectors.toMap(SysHospital::getId, f -> f));
//        List<SysPatientFollow> sysPatientFollows = sysPatientFollowService.selectAll();
//        List<SysPatientFollow> patientFollows = sysPatientFollows.stream().filter(f -> Constants.DELETE_NO.equals(f.getDelFlag())
//                && Constants.YES.equals(f.getStatus())
//                && Constants.NO.equals(f.getType())).collect(Collectors.toList());
//        Map<String, List<SysPatientFollow>> map = patientFollows.stream().collect(Collectors.groupingBy(SysPatientFollow::getPatientId));
//        for (Map.Entry<String, List<SysPatientFollow>> entry : map.entrySet()) {
//            SysPatient sysPatient = sysPatientService.selectByKey(entry.getKey());
//            if (sysPatient != null) {
//                List<SysPatientFollow> value = entry.getValue();
//                SysPatientFollow follow = value.stream().sorted(Comparator.comparing(SysPatientFollow::getFollowTime).reversed()).findFirst().get();
//                String content = follow.getContent();
//                JSONObject jsonObject = JSON.parseObject(content);
//                if (!Constants.YES.equals(follow.getSerialNumber())) {
//                    resolvingFollowData(sysPatient, jsonObject);
//                    sysPatient.setJoinProvinceId(hospitalMap.get(sysPatient.getHospitalId()).getProvinceCode());
//                    sysPatient.setJoinCityId(hospitalMap.get(sysPatient.getHospitalId()).getCityCode());
//                }else{
//                    // 患者类型
//                    String userTypeJson = jsonObject.getString("question1");
//                    JSONObject userTypeData = JSON.parseObject(userTypeJson);
//                    sysPatient.setPatientType(StringUtils.isEmpty(userTypeData.getString("val")) ? -1 : PatientTypeEnum.getKey(userTypeData.getString("val")));
//
//                    // 年龄
//                    String ageJson = jsonObject.getString("question2");
//                    JSONObject ageData = JSON.parseObject(ageJson);
//                    if (StringUtils.hasText(ageData.getString("val"))) {
//                        sysPatient.setAge(ageData.getString("val"));
//                    }
//
//                    // 性别
//                    String sexJson = jsonObject.getString("question3");
//                    JSONObject sexData = JSON.parseObject(sexJson);
//                    String val = sexData.getString("val");
//                    sysPatient.setSex(StringUtils.isEmpty(val) ? 0 : SexEnum.getKey(val));
//
//                    // 身高
//                    String heightAndWeightJson = jsonObject.getString("question13");
//                    JSONObject heightAndWeightData = JSON.parseObject(heightAndWeightJson);
//                    sysPatient.setHeight(new BigDecimal(heightAndWeightData.getString("height")));
//                    // 体重
//                    sysPatient.setWeight(new BigDecimal(heightAndWeightData.getString("weight")));
//
//                    // 当前治疗方案
//                    String treatmentPlansJson = jsonObject.getString("question11");
//                    JSONObject treatmentPlanData = JSON.parseObject(treatmentPlansJson);
//                    String planDataString = treatmentPlanData.getString("text");
//                    sysPatient.setTreatmentPlan(TreatmentPlanEnum.getKey(planDataString));
//
//                    // 治疗剂量
//                    String treatmentDosageJson = jsonObject.getString("question12");
//                    JSONObject treatmentDosageData = JSON.parseObject(treatmentDosageJson);
//                    String treatmentDosageString = treatmentDosageData.getString("val");
//                    sysPatient.setDosage(treatmentDosageString);
//                    // 频率
//                    String dosageFrequencyString = treatmentDosageData.getString("val2");
//                    sysPatient.setDosageFrequency(dosageFrequencyString);
//
//                    // 医保限额
//                    String islimitMoneyJson = jsonObject.getString("question7");
//                    JSONObject islimitMoneyData = JSON.parseObject(islimitMoneyJson);
//                    String islimitMoneyString = islimitMoneyData.getString("val");
//                    if (StringUtils.hasText(islimitMoneyString)) {
//                        sysPatient.setMedicalInsuranceLimit(Constants.YES_STRING.equals(islimitMoneyString) ? Constants.YES : Constants.NO);
//                    }
//
//                    // 医保限额
//                    String limitMoneyJson = jsonObject.getString("question7.1");
//                    JSONObject limitMoneyData = JSON.parseObject(limitMoneyJson);
//                    String limitMoneyString = limitMoneyData.getString("val");
//                    sysPatient.setMedicalInsuranceLimitMoney(limitMoneyString);
//                }
//                sysPatientService.update(sysPatient);
//            }
//        }
//    }

//    @Override
//    public void refresh() {
//        List<SysPatient> sysPatients = sysPatientService.selectAll();
//        Map<String, SysPatient> patientMap = sysPatients.stream().collect(Collectors.toMap(SysPatient::getId, f -> f));
//
//        List<SysHospital> sysHospitals = sysHospitalService.selectAllDetail();
//        Map<String, SysHospital> hospitalMap = sysHospitals.stream().collect(Collectors.toMap(SysHospital::getId, f -> f));
//
//        for (SysPatient sysPatient : sysPatients) {
//            List<SysPatientFollow> patientFollows = sysPatientFollowMapper.queryByPatientId(sysPatient.getId(), null);
//            for (SysPatientFollow patientFollow : patientFollows) {
//                patientFollow.setNurseId(sysPatient.getNurseId());
//                patientFollow.setPatientName(sysPatient.getRealName());
//                patientFollow.setPrescription(sysPatient.getPrescription());
//                patientFollow.setChangeReason(sysPatient.getChangeReason());
//                SysHospital sysHospital = hospitalMap.get(sysPatient.getHospitalId());
//                if(Objects.nonNull(sysHospital)){
//                    patientFollow.setHospitalId(sysHospital.getId());
//                    patientFollow.setHospitalType(sysHospital.getHospitalType());
//                    patientFollow.setJoinProvinceId(sysHospital.getProvinceCode());
//                    patientFollow.setJoinCityId(sysHospital.getCityCode());
//                    patientFollow.setRegion(sysHospital.getRegion());
//                    patientFollow.setBigRegion(sysHospital.getBigRegion());
//                    patientFollow.setRangeId(sysHospital.getRangeId());
//                }
//                sysPatientFollowMapper.updateByPrimaryKey(patientFollow);
//            }
//        }
//    }

    @Override
    public void refresh(List<String> patientIds) {
        List<SysPatient> sysPatients = sysPatientService.selectAll();
        if(CollectionUtils.isEmpty(patientIds)){
            for (SysPatient sysPatient : sysPatients) {
                List<SysPatientFollow> patientFollows = sysPatientFollowMapper.queryByPatientId(sysPatient.getId(), 0);
                for (SysPatientFollow patientFollow : patientFollows) {
                    patientFollow.setJoinTime(sysPatient.getJoinTime());
                    sysPatientFollowMapper.updateByPrimaryKey(patientFollow);
                }
            }
        }
    }


    @Override
    public void deletePatientFollowByPatientId(String patientId) {
        sysPatientFollowMapper.deletePatientFollowByPatientId(patientId);
    }

}
